@extends('layouts.app')
@include('shop.sidebar')
@section('content')
    <div class="content">
        <a class="btn btn-info btn-sm" href="{{ redirect()->back()->getTargetUrl() }}"> 返回 </a>
        <br/>
        <br/>
        {!! form($form) !!}
        @if (isset($flag) && $flag == 'shops')
        <div id="maplistid" -class="form-group" style="width:800px;margin: 20px 0px 0px 0px">
            <div class="input-group">
                <div class="input-group-addon no-border no-padding">
                    <span><button type="button" class="btn btn-danger faupload dz-clickable confirm">确定地点</button></span>
                </div>
                <input type="text" id="place" name="q" class="form-control" placeholder="搜索地点"/>
                <span class="msg-box n-right" for="c-image"></span>
            </div>

            <div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
            <div id="container" class="form-control" style="height: 500px"></div>
        </div>
        @endif

    </div>
@endsection
@push("stylesheets")
    <style>
        .select2-container--default .select2-selection--multiple .select2-selection__choice {
            color: gray;
        }
        label.BMapLabel {
            max-width: inherit;
            padding: .75rem 1.25rem;
            margin-bottom: 1rem;
            background-color: white;
            width: auto;
            min-width: 22rem;
            border: none;
            box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
        }
    </style>
@endpush
@push("scripts")
    <script>
        // 按照客户要求, 修改表单样式
        // 表单通过后台生成, 所以通过js调整样式
        var _form_type = "{{isset($flag) ? $flag : ''}}";
        if (_form_type == 'shops') {
            $('.content').find('form').addClass('form-inline')
            $('.content').find('form').find('label').attr('style', 'width:80px;text-align:center')
            $('.form-group').attr('style', 'margin:10px 0px;')

            $('[for="group_id"]').parent().after('<br>');
            $('[for="name"]').parent().after('<br>');
            $('[for="type_id"]').parent().after('<br>');
            $('[for="phone"]').parent().after('<br>');

            $('[for="cover"]').next('div').attr('style', 'display:inline')
            $('[for="cover"]').parent().find('br').remove();
            $('[for="cover"]').parent().find('p').attr('style', 'margin-left:10px;display:inline');
            $('[for="cover"]').parent().find('p').after('<br>');

            $('[for="description"]').parent().after('<br>');
            $('[for="description"]').parent().attr('style', 'margin:10px 0px;display:flex');
            $('[for="tag"]').parent().after('<br>');
            $('[for="category_ids[]"]').parent().after('<br>');
            $('[for="starting_price"]').parent().after('<br>');
            $('[for="features"]').parent().after('<br>');

            $('[for="video"]').next('div').attr('style', 'display:inline')
            $('[for="video"]').parent().find('br').remove();
            $('[for="video"]').parent().find('p').attr('style', 'margin-left:10px;display:inline');
            $('[for="video"]').parent().find('p').after('<br>');
            $('[for="video"]').parent().after('<br>');

            $('[name="longitude"]').attr('style', 'width:206px;');
            $('[name="latitude"]').attr('style', 'width:206px;');
            $('[for="latitude"]').parent().after('<br>');
        } else if (_form_type == 'banner') {
            $('.content').find('form').addClass('form-inline')
            $('.content').find('form').find('label').attr('style', 'width:80px;text-align:center')
            $('.form-group').attr('style', 'margin:10px 0px;')

            $('[for="image"]').next('div').attr('style', 'display:inline')
            $('[for="image"]').parent().find('br').remove();
            $('[for="image"]').parent().find('p').attr('style', 'margin-left:10px;display:inline');
            $('[for="image"]').parent().find('p').after('<br>');

            $('[for="image"]').parent().after('<br>');
            $('[for="aim"]').parent().after('<br>');
            $('[for="shop_id"]').parent().after('<br>');
            $('[for="link_id"]').parent().after('<br>');
            $('[for="link_id"]').parent().find('select').attr('style', 'width:500px;');
            $('[for="url"]').parent().after('<br>');
            $('[for="sort"]').parent().after('<br>');
        } else if (_form_type == 'recommend') {
            $('.content').find('form').addClass('form-inline')
            $('.content').find('form').find('label').attr('style', 'width:80px;text-align:center')
            $('.form-group').attr('style', 'margin:10px 0px;')

            $('[for="link_id"]').parent().after('<br>');
        }

    </script>
    <script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=C8KKFUcTebsfWFi9ypLHdo7xnFQHGIvp"></script>
    <script>
        $(".select2#groups-select").select2({
            ajax: {
                dataType: 'json',
                delay: 250,
                url: function () {
                    return '{{ route('admin.group.select') }}';
                },
                processResults: function (data) {
                    return {
                        results: $.map(data, function (row, key) {
                            return {
                                id: key,
                                text: row
                            };
                        })
                    };
                }
            }
        });

        $(".select2#user_id").select2({
            ajax: {
                dataType: 'json',
                delay: 250,
                url: function () {
                    return '{{ route('admin.search_user') }}';
                },
                processResults: function (data) {
                    return {
                        results: $.map(data, function (row, key) {
                            return {
                                id: key,
                                text: row
                            };
                        })
                    };
                }
            }
        });
        $(".select2#link_id").select2({
            ajax: {
                dataType: 'json',
                delay: 250,
                url: function () {
                    return '{{ route('admin.search_shop_good', ['shop_id' => $shop->id??0]) }}';
                },
                processResults: function (data) {
                    return {
                        results: $.map(data, function (row, key) {
                            return {
                                id: key,
                                text: row
                            };
                        })
                    };
                }
            }
        });
        tinymce.init({
            selector: '#editor',
            plugins: "textcolor colorpicker autoresize",
            menubar: false,
            // inline: true,
            toolbar: "uploadimage undo redo | fontsizeselect bold italic forecolor backcolor | alignleft aligncenter alignright alignjustify",
            images_upload_url: '/admin/upload_image?_token=' + $('meta[name="csrf-token"]').attr('content'),
            images_upload_credentials: true,
            image_dimensions: false,
            image_caption: false,
            image_description: false,
            language: 'zh_CN',
            language_url: '/tinymce/langs/zh_CN.js',
            autoresize_min_height: 350,
            autoresize_max_height: 800,
            content_style: 'img {width: 100%; height: auto; vertical-align: middle;}',
            init_instance_callback: function (editor) {
                editor.on('change', function (e) {
                    editor.save();
                });
            }
        });

        var k = [];
        <?php
            $arr = [];
            use Illuminate\Support\Facades\DB;
            $categorys = DB::select('SELECT * FROM categories WHERE PID =0 AND DELETED_AT IS NULL ORDER BY SORT DESC');
            $categorys = array_column($categorys, "name", "id");
            $sy_categorys = DB::select('SELECT * FROM categories WHERE parent ="婚纱摄影" AND DELETED_AT IS NULL  ORDER BY SORT DESC');
            $sy_categorys = array_column($sy_categorys, "name", "id");

            foreach ($categorys as $key => $value) {
                $arr[0][] = [
                    'id' => $key,
                    'text' => $value,
                ];
            }
            foreach ($sy_categorys as $key => $item) {
                $arr[1][] = [
                    'id' => $key,
                    'text' => $item,
                ];
            }
            ?>
            k = eval({!! json_encode($arr, JSON_UNESCAPED_UNICODE) !!});
        // var val = $('#type').val();
        var val = $('#type_id').find("option:selected").text();
        if (val === '{{ \App\Modules\Shop\Shop::TYPE_PHOTO }}') {
            $(".select2#category").select2({
                data: k[1],
            });
        } else {
            $(".select2#category").select2({
                data: k[0],
            });
        }

        $('#type_id').on('change', function () {
            var val = $(this).find("option:selected").text();
            $(".select2#category").html('');
            if (val === '{{ \App\Modules\Shop\Shop::TYPE_PHOTO }}') {
                $(".select2#category").select2({
                    data: k[1],
                });
            } else {
                $(".select2#category").select2({
                    data: k[0],
                });
            }
        });

        // // // 点击input 通过id 调取百度地图API功能
        $('#longitude').on('click', function () {
            // 点击空白处隐藏
            if($("#maplistid").css("display")=="none"){
                $("#maplistid").show();
            }
        });
        $('#latitude').on('click', function () {
            // 点击空白处隐藏
            if($("#maplistid").css("display")=="none"){
                $("#maplistid").show();
            }
        });
        // var map = new BMap.Map("container");
        $(function () {
            // 百度地图API功能
            function G(id) {
                return document.getElementById(id);
            }

            var map, marker, searchService, address = null, lng, lat;

            var init = function () {
                map = new BMap.Map("container"); // 创建地图实例
                var point = new BMap.Point({{isset($longitude) ? $longitude : 103.832475}}, {{isset($latitude) ? $latitude : 36.065466}}); // 创建点坐标
                map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
                map.centerAndZoom(point, parseInt("12")); // 初始化地图，设置中心点坐标和地图级别

                var size = new BMap.Size(10, 20);
                map.addControl(new BMap.CityListControl({
                    anchor: BMAP_ANCHOR_TOP_LEFT,
                    offset: size,
                }));

                var geoc = new BMap.Geocoder();

                var addpoint = function (point) {
                    //通过点击百度地图，可以获取到对应的point, 由point的lng、lat属性就可以获取对应的经度纬度
                    var pt = point;
                    geoc.getLocation(pt, function (rs) {
                        //对象可以获取到详细的地址信息
                        address = rs.address;
                        deletePoint();
                        var mk = new BMap.Marker(pt);
                        map.addOverlay(mk);
                        map.panTo(pt);
                        var label = new BMap.Label('<div class="info">地址:' + address + '<br>经度:' + pt.lng + '<br>纬度:' + pt.lat + '</div>', {offset: new BMap.Size(16, 20)});
                        label.setStyle({
                            border: 'none',
                            padding: '.75rem 1.25rem'
                        });
                        mk.setLabel(label);
                        //将对应的HTML元素设置值
                        lng = pt.lng;
                        lat = pt.lat;
                    });
                };

                if ("116.45627" != '' && "39.91999" != '') {
                    addpoint(point);
                }

                ac = new BMap.Autocomplete({"input": "place", "location": map}); //建立一个自动完成的对象
                ac.addEventListener("onhighlight", function (e) {  //鼠标放在下拉列表上的事件
                    var str = "";
                    var _value = e.fromitem.value;
                    var value = "";
                    if (e.fromitem.index > -1) {
                        value = _value.province + _value.city + _value.district + _value.street + _value.business;
                    }
                    str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

                    value = "";
                    if (e.toitem.index > -1) {
                        _value = e.toitem.value;
                        value = _value.province + _value.city + _value.district + _value.street + _value.business;
                    }
                    str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
                    G("searchResultPanel").innerHTML = str;
                });
                ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
                    var _value = e.item.value;
                    myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
                    G("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
                    setPlace();
                });

                function setPlace() {
                    map.clearOverlays();    //清除地图上所有覆盖物
                    function myFun() {
                        var result = local.getResults().getPoi(0);
                        var pp = result.point;    //获取第一个智能搜索的结果
                        map.centerAndZoom(pp, 18);
                        map.addOverlay(new BMap.Marker(pp));    //添加标注
                        lng = pp.lng;
                        lat = pp.lat;
                        address = result.address;
                    }

                    var local = new BMap.LocalSearch(map, { //智能搜索
                        onSearchComplete: myFun
                    });
                    local.search(myValue);
                }

                map.addEventListener("click", function (e) {
                    //通过点击百度地图，可以获取到对应的point, 由point的lng、lat属性就可以获取对应的经度纬度
                    var pt = e.point;
                    addpoint(e.point);
                });

                /**
                 * 清除覆盖物
                 */
                function deletePoint() {
                    var allOverlay = map.getOverlays();
                    for (var i = 0; i < allOverlay.length; i++) {
                        map.removeOverlay(allOverlay[i]);
                    }
                }
            };

            //点击确定后执行回调赋值
            $(document).on('click', '.confirm', function () {
                var zoom = map.getZoom();
                var data = {lat: lat, lng: lng, zoom: zoom, address: address};

                $('#longitude').val(data.lng)
                $('#latitude').val(data.lat)
            });

            init();
        });
    </script>
@endpush
